//
//  FSFormatTool.m
//  rui_lian_zhi_jia
//
//  Created by 代佳宏 on 2019/9/25.
//  Copyright © 2019 华宇瑞联. All rights reserved.
//

#import "FSFormatTool.h"
#import<SystemConfiguration/CaptiveNetwork.h>
#import <NetworkExtension/NetworkExtension.h>
@implementation FSFormatTool
+ (NSString *)formatPriceWithPrice:(NSNumber *)price {
    if(nil == price || 0 == price.integerValue)
        return @"0";
    
    return [NSString stringWithFormat:@"%.0f", price.floatValue / 100];
}

//是否需要￥符号
+ (NSString *)formatPriceWithPrice:(NSNumber *)price symbol:(BOOL)symbol{
  
    if(nil == price || 0 == price.integerValue){
        return symbol ? @"￥ 0" : @"0";
    }
    
    if ((price.integerValue % 10) > 0) {
        return symbol ? [NSString stringWithFormat:@"¥ %.2f", price.integerValue / 100.0] : [NSString stringWithFormat:@"%.2f", price.integerValue / 100.0];
    }else if ((price.integerValue % 100) > 0) {
        return symbol ? [NSString stringWithFormat:@"¥ %.1f", price.integerValue / 100.0] : [NSString stringWithFormat:@"%.1f", price.integerValue / 100.0];
    }else{
        return symbol ? [NSString stringWithFormat:@"¥ %ld", price.integerValue / 100] : [NSString stringWithFormat:@"%ld", price.integerValue / 100];
    }
    
}

+ (NSString *)formatStockWithQuantity:(NSNumber *)quantity {
    if(nil == quantity)
        return @"暂无库存";
    
    return [NSString stringWithFormat:@"%@ 瓶", quantity];
}

+ (NSString *)formatDateStringWithDateString:(NSString *)dateString
                             SourceFormatter:(NSDateFormatter *)sourceFormatter
                               DestFormatter:(NSDateFormatter *)destFormatter {
    NSDate * date = [sourceFormatter dateFromString:dateString];
    if(nil == date)
        return @"";
    
    return [destFormatter stringFromDate:date];
}
//date转字符串 yyyy-MM-dd HH:mm:ss
+ (NSString *)formatDateTime:(NSDate *)dataTime format:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSString *strDate = [dateFormatter stringFromDate:dataTime];
    return strDate;
}
//字符串转date
+ (NSDate *)formatStrTime:(NSString *)strTime format:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    NSDate *dayDate = [dateFormatter dateFromString:strTime];
    return dayDate;
}

+ (NSString *)formatDateWithTimeString:(NSString *)timeString{
  NSTimeInterval time = [timeString doubleValue];
    time = time/1000;
  NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  return [dateFormatter stringFromDate: detaildate];
}

+ (NSString *)formatDateWithTimeInterval:(NSInteger)time{
   time = time/1000;
  NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"MM/dd"];
  return [dateFormatter stringFromDate: date];
}
+ (NSString *)formatDateWithTimeIntervalYear:(NSInteger)time{
    time = time/1000;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy.MM.dd"];
    return [dateFormatter stringFromDate: date];
}
+ (NSString *)formatDateStrWithTimeInterval:(NSInteger)time format:(NSDateFormatter *)format{
   NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
  return [format stringFromDate:date];
}
//时间戳转日期格式(根据时间格式格式样式)
+ (NSString *)formatDateStrWithTimeInterval:(NSInteger)time formatStr:(NSString *)formatStr{
    time= time/1000;
  NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
  NSDateFormatter *fr = [[NSDateFormatter alloc]init];
  [fr setDateFormat:formatStr];
  return [fr stringFromDate:date];
}
//获取当前年月ri
+ (NSString *)stringMonthFromNowDate{
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *fmr = [[NSDateFormatter alloc]init];
    [fmr setDateFormat:@"yyyy-MM-dd"];
    NSString *str = [fmr stringFromDate:nowDate];
    return str;
}
//获取当前年月ri
+ (NSString *)stringMonthFrom{
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *fmr = [[NSDateFormatter alloc]init];
    [fmr setDateFormat:@"yyyy-MM"];
    NSString *str = [fmr stringFromDate:nowDate];
    return str;
}

+(NSString *)getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
    
}

+(NSString *)getWifiNameSsid{
    NSString *ssid = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
        ssid = info[@"SSID"];
        }
    }
    return ssid;
}

+ (UIColor *)colorWithHexString:(NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;

    //r
    NSString *rString = [cString substringWithRange:range];

    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
+ (UIColor *)colorWithHexStringAL:(NSString *)color alpha:(CGFloat)alpha
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;

    //r
    NSString *rString = [cString substringWithRange:range];

    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:alpha];
}

+ (BOOL)validateContactNumber:(NSString *)mobileNum
{
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 16[6], 17[5, 6, 7, 8], 18[0-9], 170[0-9], 19[89]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705,198
     * 联通号段: 130,131,132,155,156,185,186,145,175,176,1709,166
     * 电信号段: 133,153,180,181,189,177,1700,199
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|6[6]|7[05-8]|8[0-9]|9[89])\\d{8}$";

    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478]|9[8])\\d{8}$)|(^1705\\d{7}$)";
   
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|66|7[56]|8[56])\\d{8}$)|(^1709\\d{7}$)";

    NSString *CT = @"(^1(33|53|77|8[019]|9[019])\\d{8}$)|(^1700\\d{7}$)";
    
    /**
     * 大陆地区固话及小灵通
     * 区号：010,020,021,022,023,024,025,027,028,029
     * 号码：七位或八位
     */
   // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
   // NSPredicate *regextestPHS = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    if(([regextestmobile evaluateWithObject:mobileNum] == YES)
       || ([regextestcm evaluateWithObject:mobileNum] == YES)
       || ([regextestct evaluateWithObject:mobileNum] == YES)
       || ([regextestcu evaluateWithObject:mobileNum] == YES)) {
        return YES;
    } else {
        return NO;
    }
}


+ (void)writeUserDataWithKey:(id)data forKey:(NSString*)key
{
    if (data == nil){
        return;
    }else {
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

//读取用户偏好设置
+ (id)readUserDataWithKey:(NSString*)key
{
    id temp = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if(temp != nil){
        return temp;
    }
    
    return nil;
}


+(NSString*)cronStringWithtime:(long long)time
                          week:(NSInteger)week
                       weekday:(NSInteger)weekday
{
    NSString* cron;
    
    long hour = time / 3600;
    long min = time / 60 % 60;
    long second = time % 60;
    
    //执行一次 应该设置 日月年, tbd.
    NSString* weekDesp=@"";
    if(week == 0){ //once
        weekDesp = @"?";
        NSDate* date = [NSDate date];
        NSCalendar * calendar = [NSCalendar currentCalendar]; // 指定日历的算法
        NSDateComponents *comps = [calendar components:kCFCalendarUnitSecond|NSCalendarUnitMinute|NSCalendarUnitHour|NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:date];
        long long currentTime=comps.hour*60*60+comps.minute*60+comps.second;
        if (currentTime>=time) {
            NSDate *tomorrowDate = [NSDate dateWithTimeIntervalSinceNow:(24*60*60)];
            comps=[calendar components:kCFCalendarUnitSecond|NSCalendarUnitMinute|NSCalendarUnitHour|NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:tomorrowDate];
        }
        cron = [NSString stringWithFormat:@"%ld %ld %ld %ld %ld %@ %ld",second,min,hour,comps.day,comps.month,weekDesp,comps.year];
        return cron;
    }else if(week == 127){ //every day
        weekDesp = @"*";
    }else{
        NSMutableString *weekString = [NSMutableString new];
        NSInteger weekIndex = 0;
        while (week) {
            if (week & 0x1) {
                if (0 != weekString.length) {
                    [weekString appendString:@","];
                }
                [weekString appendFormat:@"%ld", weekIndex+1]; //cron from 1-7
            }
            week >>= 1;
            ++weekIndex;
        }
        weekDesp = weekString;
    }
    
    //Seconds Minutes Hours Day-of-Month Month Day-of-Week Year
    cron = [NSString stringWithFormat:@"%ld %ld %ld ? * %@ *",second,min,hour,weekDesp];   //cron = @"0 0 8 ? * 2,3,4,5,6 *";
    
    return cron;
}

+ (NSString *)arrayToJSONString:(NSArray *)array

 {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}



+(NSInteger)compareDate:(NSString*)aDate withDate:(NSString*)bDate{


    NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];

    [dateformater setDateFormat:@"yyyy-MM-dd"];

    NSDate *dta = [[NSDate alloc]init];

    NSDate*dtb = [[NSDate alloc]init];


    dta = [dateformater dateFromString:aDate];

    dtb = [dateformater dateFromString:bDate];

    NSComparisonResult result = [dta compare:dtb];


    if (result == NSOrderedDescending) {
        //指定时间 已过期
        return 1;
    }else if(result == NSOrderedAscending){

        //指定时间 没过期
        return -1;
    }else{
        //刚好时间一样.
        return 0;
    }


}
@end


